const BaseController = require('../core/BaseController');

module.exports = class extends BaseController {
  constructor(props) {
    super(props);
    this.tableName = 'role';
  }

  async get() {
    const { ctx, app } = this;
    const rs = await app.mysql.get(this.tableName, { id: ctx.query.id });
    const list = await app.mysql.select('role_permission', {
      where: { delete_time: null, role_id:ctx.query.id }
    });
    rs.permissionIds = list.length > 0 ? list.map(item => item.permission_id) : [];
    return rs && rs.id > 0 ? ctx.success(ctx.helper.toPlainObject(rs)) : ctx.fail('找不到这个ID相关的数据');
  }

  async updateByIds() {
    const { ctx, app } = this;
    const { ids, role_id } = ctx.request.body;
    let rs = await app.mysql.beginTransactionScope(async conn => {
      try {
        await conn.delete('role_permission', { role_id });
        if(!Array.isArray(ids)){
          ids = JSON.parse(ids);
        }
        for (let i = 0; i < ids.length; i++) {
          await conn.insert('role_permission', { permission_id: ids[i], role_id });
        }
        return true;
      } catch (error) {
        return false;
      }
      
    });
    return rs ? ctx.success() : ctx.fail('更新权限失败');
  }

}

